import { Component } from 'react';
import Router from 'next/router';
import api from './api';
import checkLoggedIn from './utils/check-logged-in';

import * as userActions from './reudx/userAuth/actions';

const { setUserAuth } = userActions;

const roleMap = {
	1: 'student',
	2: 'teacher',
	3: 'manager' 
};

function redirect(ctx, target) {
	if (ctx.res) {
		ctx.res.writeHead(303, { Location: target });
		ctx.res.end();
	} else {
		Router.replace(target);
	}
}

function isNotCurrentRole(ctx, role) {
	const pathname = ctx.pathname;
	const url = ctx.req.url;
	return (pathname && pathname.indexOf(roleMap[role]) === -1) || (url && url.indexOf(roleMap[role]) === -1);
}

function withCtx(Child) {
	return class WrappedComponent extends Component {
		static async getInitialProps(ctx) {
			const { store } = ctx;

			if (ctx.req) {
				ctx.isServer = true;
			} else {
				ctx.isServer = false;
			}

			if (!store.getState().userAuth.id) {
				const userInfo = await checkLoggedIn(ctx);
				if (userInfo && userInfo.id && userInfo.role) {
					// 已经记住登录状态
					const role = userInfo.role;
					store && store.dispatch(setUserAuth(userInfo));
					if ((ctx.pathname && ctx.pathname === '/user/login') || (ctx.req && ctx.req.url === '/user/login')) {
						redirect(ctx, `/${roleMap[role]}`);
					} else {
						if (isNotCurrentRole(ctx, role)) {
							redirect(ctx, `/${roleMap[role]}`);
						}
					} 
				} else {
					// 没有登录，默认跳到登录页
					if ((ctx.pathname && ctx.pathname !== '/user/login') || (ctx.req && ctx.req.url !== '/user/login')) {
						redirect(ctx, '/user/login');
					}
				}
			} 

			return Child.getInitialProps(ctx);
		}
		render () {
			return <Child {...this.props} />
		}
	}
}

export default withCtx;